#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2020/4/13 0013 21:43
# @Author  : liangshuo
# @File    : 01-db.py
# @Software : PyCharm

import os
import sys
import datetime

import MySQLdb


def test(db_config):
    # 打开数据库连接
    now_date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    db = MySQLdb.connect(host=db_config.get('HOST'),
                         port=db_config.get('PORT'),
                         user=db_config.get('USER'),
                         passwd=db_config.get('PASSWORD'),
                         db=db_config.get('DATABASE'),
                         charset='utf8')

    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()

    # SQL 删除语句
    sql = "DELETE  FROM `salt_returns` where datediff(NOW(),alter_time) >= 1"
    try:
        # 执行SQL语句
        ret = cursor.execute(sql)
        # 提交修改
        db.commit()

        print('【%s条】 delete salt_returns data success ############# %s ' % (ret, now_date))
    except Exception as e:
        # 发生错误时回滚
        db.rollback()
        print('delete salt_returns data failed ############# %s' % now_date)

    # 关闭连接
    cursor.close()

    # 关闭数据库连接
    db.close()


if __name__ == '__main__':
    SALT_DATABASE = {
        'DATABASE': 'goms',
        'USER': 'salt',
        'PASSWORD': 'Giantsre@2019',
        'HOST': '192.168.23.21',
        'PORT': 3306,
    }
    db_config = SALT_DATABASE
    test(db_config)
